package com.life.controller;

import java.util.ArrayList;
import java.util.HashMap;

import com.life.model.LifeModel;
import com.life.model.event.ModelBoardResetEvent;
import com.life.model.event.ModelBoardRuleSetEvent;
import com.life.model.event.ModelBoardUpdateEvent;
import com.life.rule.ILifeRule;
import com.life.utils.LoggerUtil;
import com.life.view.AbstractAdapter;

public class LoggerController extends AbstractController {

	HashMap<Integer,LifeModel> map = new HashMap<Integer,LifeModel>();
	AbstractAdapter simulationSliderAdapter = null;
	boolean ignoreUpdate = false;
	ILifeRule queuedUpRule = null;
	ArrayList lifeCount = new ArrayList();
	
	public LoggerController(LifeModel model, ArrayList<AbstractAdapter> adapterList) {
		super(model, adapterList);
		model.addModelEventsListener(this);
		
		
		simulationSliderAdapter = adapterList.get(0);
	}

	@Override
	public void doUpdate(AbstractAdapter source, Object data) {
		
	    if(source == simulationSliderAdapter)
	    {
		int val = Integer.parseInt(source.get().toString());
		setModelBoardatGeneration(val);
		
	    }
	    

	}
	
	public void modelBoardUpdated(ModelBoardUpdateEvent event) {
		
	    if(!ignoreUpdate)
	    {
		LoggerUtil.put(new Integer(event.getModel().getGenerationCount()),
			            event.getModel().getRawBoardCopy(),
			            event.getModel().getLifeCount(),
			            event.getModel().getCurrentRule());
	    }
	}
	
	public void setModelBoardatGeneration(int value)
	{
	    boolean[][] archivedModel = LoggerUtil.get(new Integer(value));
	    
	    if(archivedModel != null)
	    {
		//System.out.println("replacing board");
		ignoreUpdate =true;
		theModel.replaceRawBoard(archivedModel,value);
		ignoreUpdate = false;
	    }
	}
	
	public void modelBoardReset(ModelBoardResetEvent event)
	{
	    LoggerUtil.reset();
	}
	
	public void modelRuleSet(ModelBoardRuleSetEvent event)
	{
		queuedUpRule = event.getRule();
	}

}
